//
//  TWBOAuthViewController.swift
//  weiBo
//
//  Created by 杨雷 on 2016/12/12.
//  Copyright © 2016年 Yang.L. All rights reserved.
//

import UIKit
import SVProgressHUD


let AppKey = "111263498"
let AppSecret = "7849fcb1a3700edf2a5401ac6b916b40"
let Redirect_uri = "http://www.qq.com"

class TWBOAuthViewController: UIViewController {

    private lazy var webView: UIWebView = UIWebView()
    
    override func loadView() {
        
        webView.delegate = self
        
        view = webView
    }
    
    override func viewDidLoad() {
        
        super.viewDidLoad()
        
        setNavUI()
        
        loadRequest()
        
    }

    private func setNavUI() {
        
        webView.isOpaque = false
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: #selector(cancelAction))
        
        navigationItem.title = "微博登录"
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(autoFillAction))
        
    }
    
    @objc private func cancelAction () {
        
        SVProgressHUD.dismiss()
        
        dismiss(animated: true, completion: nil)
        
    }
    
    @objc private func autoFillAction () {
        
        webView.stringByEvaluatingJavaScript(from: "document.getElementById('userId').value = 'hao123guohaibin@163.com'; document.getElementById('passwd').value = 'guohaibin123'")
    }
    
    private func loadRequest() {
        
        let url = "https://api.weibo.com/oauth2/authorize?client_id=\(AppKey)&redirect_uri=\(Redirect_uri)"
        
        let urlRequest = URLRequest(url: URL(string: url)!)
        
        webView.loadRequest(urlRequest)
    }
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
}

extension TWBOAuthViewController: UIWebViewDelegate {
    
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        guard let url = request.url else {
            
            return false
        }
        if !url.absoluteString.hasPrefix(Redirect_uri) {
            
            return true
        }
        
        if let query = url.query, query.hasPrefix("code=") {
            
            let startIndex = "code-".endIndex
            
            let code = query.substring(from: startIndex)
            
            TWBUserAccountViewModel.sharedUserAccount.requestAccessToken(code: code, callBack: { (isSuccess) in
                
                if isSuccess {
                    self.dismiss(animated: false, completion: { 
                        
                        NotificationCenter.default.post(name: NSNotification.Name(SwitchRootVCNotificationName), object: self)
                        
                    })
                    
                } else {
                    print("登陆失败")
                }
                
            })
            
        } else {
            
            dismiss(animated: true, completion: nil)
        }
        
        return false
    }
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        
        SVProgressHUD.dismiss()
    }
    
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        
        SVProgressHUD.dismiss()
    }
    
    
}


